const request = require('../../utils/request');
const appKey = require('../../config/appKey');
const common = require('../../utils/common');
class Synchronize {
    /**
     * 同步设备列表
     * @api {GET}         /drives               同步设备列表
     * @apiName           /Synchronize/drives
     * @apiGroup          Synchronize
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "Success",
        "data": []
       }
     */
    async drives(ctx) {
        const { db } = ctx;
        const url =
            'http://xicheba.net/cdyangyang/API/Handler/DevList?apiKey=' +
            appKey.appKey;
        let data = await request.get(url);
        data = JSON.parse(JSON.stringify(data.data));
        // console.log(data);
        for (let i = 0; i < data.length; i++) {
            // 生成二维码
            const src = await common.createCode(data[i].DeviceCode);
            let condition = {
                where: {
                    deviceId: data[i].DeviceCode
                }
            };
            let drives = await db.Drives.findOne(condition);
            if (drives) {
                drives.areaName = data[i].AreaName;
                drives.isOnline = data[i].IsOnline;
                drives.useState = data[i].UseState;
                drives.src = src;
                drives.save();
            } else {
                db.Drives.upsert({
                    merchantId: 0,
                    deviceId: data[i].DeviceCode,
                    areaName: data[i].AreaName,
                    isOnline: data[i].IsOnline,
                    useState: data[i].UseState,
                    src: src
                });
            }
        }
        ctx.success();
    }
}
module.exports = new Synchronize();
